package com.sskj.api.controller.admin;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.sskj.api.annotation.LoginLog;
import com.sskj.api.domain.SysUser;
import com.sskj.api.exception.LogicException;
import com.sskj.api.service.ISysUserService;
import com.sskj.api.vo.req.AdminLoginReq;
import com.sskj.api.vo.resp.AuthInfoResp;
import com.sskj.common.util.ApiResponseUtil;
import com.sskj.common.util.StrUtil;
import com.sskj.common.vo.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "认证模块")
@RestController
@RequestMapping("/admin/auth")
@Validated
public class AuthController {

    @Autowired
    private ISysUserService adminUserService;

    @LoginLog
    @Operation(summary = "用户登录")
    @PostMapping("doLogin")
    public ApiResponse<AuthInfoResp> login(@Valid @RequestBody AdminLoginReq adminLoginReq) {
        if (adminLoginReq.getType() == 1) {
            if (StrUtil.isBlank(adminLoginReq.getPassword()) || StrUtil.isBlank(adminLoginReq.getPhone())) {
                throw new LogicException("缺少必要的请求参数");
            }
            SysUser sysUser = adminUserService.accountLogin(adminLoginReq.getPhone(), adminLoginReq.getPassword());

            StpUtil.login(sysUser.getId());
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            AuthInfoResp authInfoResp = new AuthInfoResp();
            authInfoResp.setTokenName(tokenInfo.getTokenName());
            authInfoResp.setAccessToken(tokenInfo.getTokenValue());

            return ApiResponseUtil.success(authInfoResp);
        } else {
            throw new LogicException("无效的登录类型");
        }
    }
}
